import { getCartList, changeCount, delSelect } from '@/api/cart'
import { showToast } from 'vant'

export default {
  namespaced: true,
  state() {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList(state, newList) {
      state.cartList = newList
    },
    toggleCheck(state, goodsId) {
      const good = state.cartList.find((item) => item.goods_id === goodsId)
      good.isChecked = !good.isChecked
    },
    toggleAllCheck(state, isAllChecked) {
      state.cartList.forEach((item) => {
        item.isChecked = !isAllChecked
      })
    },
    changeCount(state, data) {
      const { goodsNum, goodsId } = data
      state.cartList.find((item) => item.goods_id === goodsId).goods_num =
        goodsNum
    }
  },
  actions: {
    async getCartAction(context) {
      const {
        data: { list }
      } = await getCartList()
      list.forEach((element) => {
        element.isChecked = true
      })
      context.commit('setCartList', list)
    },
    async changeCountAction(context, obj) {
      const { goodsNum, goodsId, goodsSkuId } = obj
      context.commit('changeCount', { goodsNum, goodsId })
      await changeCount(goodsNum, goodsId, goodsSkuId)
    },
    // 删除购物车数据
    async delSelect(context) {
      const selCartList = context.getters.selCartList
      const cartIds = selCartList.map((item) => item.id)
      await delSelect(cartIds)
      showToast('删除成功')

      // 重新渲染数据
      context.dispatch('getCartAction')
    }
  },
  getters: {
    cartTotal(state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的商品项
    selCartList(state) {
      return state.cartList.filter((item) => item.isChecked)
    },
    // 选中的总数
    selCount(state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的总价
    selPrice(state, getters) {
      return getters.selCartList
        .reduce(
          (sum, item) => sum + item.goods_num * item.goods.goods_price_min,
          0
        )
        .toFixed(2)
    },
    // 是否全选
    isAllChecked(state) {
      return state.cartList.every((item) => item.isChecked === true)
    }
  }
}
